package spzx.service.impl;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.MinioException;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import spzx.exception.SpzxException;
import spzx.service.FileUploadService;

import java.io.InputStream;
import java.util.UUID;

@Service
public class FileUploadServiceImpl implements FileUploadService {

    @Override
    public String upload(MultipartFile multipartFile) {
        try {
            //0.校验上传的文件是否为图片格式-->判断文件后缀名是否为png、jpg、jpeg、gif
            String originalFileName = multipartFile.getOriginalFilename();
            if (!originalFileName.endsWith("png") && !originalFileName.endsWith("jpg") && !originalFileName.endsWith("jpeg") && !originalFileName.endsWith("gif")){
                throw new SpzxException(501,"上传的文件格式不正确，请上传图片格式的文件！");
            }

            //1.创建minioClient对象
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint("http://192.168.188.128:9000")
                            .credentials("admin", "admin123456")
                            .build();
            //2.判断桶是否存在，若不在创建一个
            // Make 'asiatrip' bucket if not exist.
            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket("spzx-sysuser-avator").build());
            if (!found) {
                // Make a new bucket called 'asiatrip'.
                minioClient.makeBucket(MakeBucketArgs.builder().bucket("spzx-sysuser-avator").build());
            } else {
                System.out.println("Bucket 'spzx-sysuser-avator' already exists.");
            }

            //3.上传文件

            InputStream inputStream = multipartFile.getInputStream();

            //4.生成唯一文件名
            String objectName = UUID.randomUUID().toString().replaceAll("-", "") + originalFileName;
            //5.调用api实现文件上传
            minioClient.putObject(
                    PutObjectArgs.builder()
                            .bucket("spzx-sysuser-avator")
                            .object(objectName)
                            .stream(inputStream, inputStream.available(), -1)
                            .contentType(originalFileName.endsWith(".jpg")? "image/jpeg" : "image/png")
                            .build()
            );
            System.out.println("File uploaded successfully");

            String url = "http://192.168.188.128:9000/spzx-sysuser-avator/" + objectName;

            return url;

        } catch (Exception e) {
            throw new SpzxException(501,"上传文件失败！");
        }
    }
}
